<template>
  <div class="prompt-container" v-if="isVisible">
    <div class="prompt-box">
      <h2>{{ title }}</h2>
      <input type="text" ref="inputSelectBound" v-model="inputValue" />
      <button @click="confirmInput">确定</button>
      <button @click="cancelPrompt">取消</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
const inputSelectBound = ref(null)
const isVisible = ref(false);
let resolvePromise = null;
let rejectPromise = null;
let promise = new Promise((res, rej) => {
  resolvePromise = res;
  rejectPromise = rej;
});

const title = ref("标题");
const inputValue = ref("");

const showPrompt = (newTitle) => {
  title.value = newTitle || title.value;
  isVisible.value = true;
  nextTick(() => {
    inputSelectBound.value.focus()
  })
  return promise;
};

const confirmInput = () => {
  isVisible.value = false;
  resolvePromise(inputValue.value);
  console.log(promise);
  inputValue.value = ''
  resolvePromise = null;
  rejectPromise = null;
  promise = new Promise((res, rej) => {
    resolvePromise = res;
    rejectPromise = rej;
  });
};

const cancelPrompt = () => {
  isVisible.value = false;
  resolvePromise('取消');
};
defineExpose({
    isVisible,
    resolvePromise,
    rejectPromise,
    promise,
    inputValue,
    showPrompt,
    confirmInput,
    cancelPrompt
})
</script>

<style scoped>
.prompt-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
 
.prompt-box {
  background-color: #fff;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}
 
input {
  padding: 8px;
  margin-bottom: 10px;
  width: 200px;
}
 
button {
  padding: 8px 15px;
  margin: 5px;
  cursor: pointer;
}
</style>